package xiu_xiu.utils.ui;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;


import java.util.ArrayList;
import java.util.List;

import xiu_xiu.base.MyApplication;

public class UiUtils {
    /**
     * 获得一个空间的宽高   防0
     */

    public static void setViewMeasure(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    }

    /**
     * 从资源文件获取一个view
     */
    public static View getInflaterView(Context context, int res) {
        View view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(res, null);
        applyFont(view);
        return view;
    }

    /**
     * 从资源文件获取一个view
     */
    public static View getInflaterView(Context context, int res, ViewGroup parent) {
        View view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(res, parent);
        applyFont(view);
        return view;
    }

    /**
     * 从资源文件获取一个view
     */
    public static View getInflaterView(Context context, int res, ViewGroup parent, boolean attachToRoot) {
        View view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(res, parent, attachToRoot);
        applyFont(view);
        return view;
    }


    @SuppressLint("ClickableViewAccessibility")
    public static void setButtonClickTint(final View view, final int colorUp,
                                          final int colorDown) {

        if (view instanceof ImageView) {
            view.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            ((ImageView) view).setColorFilter(view.getResources()
                                    .getColor(colorDown));
                            break;
                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            ((ImageView) view).setColorFilter(view.getResources()
                                    .getColor(colorUp));
                            break;

                        default:
                            break;
                    }

                    return false;
                }
            });
            // 设置字体点击后的文字颜色变化
        } else if (view instanceof TextView) {
            view.setOnTouchListener(new OnTouchListener() {

                @SuppressLint("ClickableViewAccessibility")
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {

                        case MotionEvent.ACTION_DOWN:
                            ((TextView) view).setTextColor(view.getResources()
                                    .getColor(colorDown));
                            break;
                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            ((TextView) view).setTextColor(view.getResources()
                                    .getColor(colorUp));
                            break;

                        default:
                            break;
                    }

                    return false;
                }
            });
        }
    }

    /*
     * 设置ImageView渲染（Tint）
     */
    public static void setImageViewTint(final ImageView view, final int color) {
        view.setColorFilter(view.getResources().getColor(color));
    }

    /**
     * 设置字体
     */
    public static void applyFont(final View root) {
        try {
            if (root instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) root;
                for (int i = 0; i < viewGroup.getChildCount(); i++)
                    applyFont(viewGroup.getChildAt(i));
            } else if (root instanceof TextView)
                ((TextView) root).setTypeface(((MyApplication) (root.getContext().getApplicationContext())).typeface);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context
     */
    public static boolean isForeground(Context context) {
        if (context instanceof Activity) {
            String className = context.getClass().getName();
            if (context == null || TextUtils.isEmpty(className)) {
                return false;
            }

            ActivityManager am = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
            if (list != null && list.size() > 0) {
                ComponentName cpn = list.get(0).topActivity;
                if (className.equals(cpn.getClassName())) {
                    return true;
                }
            }
        }
        return false;

    }

    /**
     * 缩放动画，先放大，后缩小，   用于提醒用户状态的变化
     */
    public static void scaleAnim(View view, float scaleMax, float scaleMin, int duration) {

        PropertyValuesHolder scx = PropertyValuesHolder.ofFloat("scaleX", 1, scaleMax, 1, scaleMin, 1);
        PropertyValuesHolder scY = PropertyValuesHolder.ofFloat("scaleY", 1, scaleMax, 1, scaleMin, 1);

        ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(
                view, scx, scY).setDuration(duration);
        objectAnimator.start();
    }


    /**
     * 得到viewGroup里面的numberpicker组件
     *
     * @param viewGroup
     * @return
     */
    private static List<NumberPicker> findNumberPicker(ViewGroup viewGroup) {
        List<NumberPicker> npList = new ArrayList<NumberPicker>();
        View child = null;
        if (null != viewGroup) {
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                child = viewGroup.getChildAt(i);
                if (child instanceof NumberPicker) {
                    npList.add((NumberPicker) child);
                } else if (child instanceof LinearLayout) {
                    List<NumberPicker> result = findNumberPicker((ViewGroup) child);
                    if (result.size() > 0) {
                        return result;
                    }
                }
            }
        }
        return npList;
    }


    /**
     * 设置列表控件是否可以滚动，并且让下拉刷新控件一直转动，直到再次调用该方法
     *
     * @param swipeRefreshLayout 下拉刷新控件
     * @param view               列表控件
     * @param whetherRoll        是否滚动
     */
    public static void setRoll(final SwipeRefreshLayout swipeRefreshLayout, View view, final boolean whetherRoll) {

        //设置下拉刷新转动
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(whetherRoll);
            }
        });

        //设置列表控件是否可以滚动
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return whetherRoll;
            }
        });
    }


}